//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
//

#include "AnalyzeUnit.h"

Define_Module(AnalyzeUnit);

void AnalyzeUnit::initialize()
{
	this->m_MessageNum = 0;
	this->m_UtilSum = 0;
	this->m_UtilizationTime.setName("Utilization Time");
	this->m_TimeInRouter.setName("Time in Router");
	this->m_QueueSize.setName("Queue Size");
}

//Receives and deletes the messages while collecting statistics
void AnalyzeUnit::handleMessage(cMessage *msg)
{
	NetworkPacket* packet = dynamic_cast<NetworkPacket*>(msg);
	if(packet != NULL)
	{
		double util_time = (simTime() - packet->getSendingTime()).dbl();
		this->m_UtilSum += util_time;
		this->m_UtilizationTime.record(util_time);

		//checks if this is the last fragment
		if(packet->getKind() == LAST_FRAGMENT)
		{
			this->m_TimeInRouter.record(packet->getSendingTime() - packet->timeStamp);
		}
		this->m_QueueSize.record(packet->entrySizeOfQueue);

		ev<<"Received message: "<< this->m_MessageNum++ << " At simulation time: " << simTime() << endl;
	}
	delete msg;
}

//records scalars for utilization time
void AnalyzeUnit::finish()
{
	recordScalar("Utilization total", this->m_UtilSum);
	recordScalar("Total simulation time", simTime());
	recordScalar("Utilization(%)", (this->m_UtilSum / simTime()) * 100);
	ev<<"Utilization sum is: "<< this->m_UtilSum <<endl;
}



